var express = require('express');
var router = express.Router();
const UsersModel = require('../../models/UsersModel');
const md5 = require('md5');


//设置注册接口
router.get('/reg',(req, res) => {
  res.render('auth/reg');
});

//设置登录页面
router.post('/reg',(req, res) => {
  UsersModel.create({...req.body,password:md5(req.body.password)},(error,data) => {
    if (error) {
      res.status(500).message('注册失败');
      return;
    }
    res.render('success',{msg:"注册成功",url:'/login'});
  });
});


router.get('/login',(req, res) => {
  res.render('auth/login');
});
router.post('/login',(req, res) => {
  let {username,password} = req.body;
  UsersModel.findOne({username:username,password:md5(password)}, (error,data) => {
    if (error) {
      res.status(500);
      return res.send('出错了');
    }
    if (!data) {
      return res.send('账号和密码错误~~~');
    }
    req.session.username = data.username;
    req.session._id = data._id;
    res.render('success',{msg:'登录成功',url:'/accounts'})
  })
});

//为了方式跨域的攻击
router.post('/logout',(req, res) => {
  req.session.destroy(() => {
    res.render('success',{msg:'退出成功',url:'/login'})
  });
});

module.exports = router;
